package com.ruoyi.bole.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单文本邮件
     * @param to 收件人邮箱地址
     * @param subject 邮件主题
     * @param text 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        message.setFrom("444619264@qq.com");
        mailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     * @param to 收件人邮箱地址
     * @param subject 邮件主题
     * @param text 邮件内容
     * @param filePath 附件文件路径
     * @throws MessagingException 邮件发送异常
     */
    public void sendMailWithAttachment(String to, String subject, String text, String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);
        helper.setFrom("your_email@qq.com");

        File file = new File(filePath);
        helper.addAttachment(file.getName(), file);
        mailSender.send(message);
    }
}    